import React from 'react';
import { Space, Table, Rate, Form, Modal } from 'antd';
import  { useEffect, useState } from 'react';
import axios from 'axios'

const request = axios.create({
  baseURL: "http://localhost:8080"
});

var store = window.localStorage

const download = (article_id) => {
  axios.post('/api/downloadArticle',
    {
      "id": article_id,
    }, {responseType: "arraybuffer"}).then(
      res => {
        let blob = new Blob([res.data],{type: 'application/vnd.ms-excel'});
        // const url = window.URL.createObjectURL(new Blob([res.data]));
        const url = window.URL || window.webkitURL || window.moxURL;
        const link = document.createElement('a'); //创建a标签
        link.href = url.createObjectURL(blob);
        link.style.display = 'none';
        link.download = res.headers['content-disposition'].split(';')[1].split('=')[1];
        document.body.appendChild(link);
        link.click();
        URL.revokeObjectURL(link.href); // 释放 URL对象
        document.body.removeChild(link);
      }
    );
}

var dataSource;

const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
  const [form] = Form.useForm();
  return (
    <Modal
      open={open}
      title="资料评价"
      okText="确定"
      cancelText="取消"
      onCancel={onCancel}
      // 真正的上传在这里
      onOk={() => {
        form
          .validateFields()
          .then((values) => {
            form.resetFields();
            onCreate(values);
          })
          .catch((info) => {
            console.log('Validate Failed:', info);
          });
      }}
    >
      <Form
        form={form}
        layout="vertical"
        name="form_in_modal"
        initialValues={{
          modifier: 'public',
        }}
      >
        <Form.Item
          name="score"
          rules={[
            {
              required: true,
              message: '打分至少有1星!',
            },
          ]}
        >
          <Rate />
        </Form.Item>
      </Form>
    </Modal>
  );
};


const Table1 = () => {
  const [open, setOpen] = useState(false);
  const [TableData, setTableData] = useState("")
  const onCreate = (values) => {
    var score_id = store.getItem("ScoreID")
    var user_name = store.getItem("UserName")
    console.log('Received values of form: ', values);
    var score_data = {
      "username": user_name,
      "id": score_id,
      "score": values.score
    }
    request.post('/api/addScore', score_data).then(  
      res => {  
        console.log(res.data)
        alert("评分成功！")
        window.location.reload()
      }
    ).catch(res => {  // 错误处理
      console.log(res.data.res)
    })
    setOpen(false);
  };
  const columns1 = [
    {
      title: '名称',
      dataIndex: 'title',
      key: 'index',
    },
    {
      title: '上传用户',
      dataIndex: 'uploader',
      key: 'index',
    },
    {
      title: '平均评分',
      dataIndex: 'avg_score',
      key: 'index',
    },
    {
        title: '我的评分',
        dataIndex: 'my_score',
        key: 'index',
    },
    {
        title: '下载',
        key: 'index',
        render: (index) => (
            <Space size="middle">
              <a onClick={() => download(index.id)}>下载</a>
            </Space>
        ),
    },
    {
        title: '评价',
        key: 'index',
        render: (index) => { 
          
          return (
            <Space size="middle">
              <div>
              <a
                    onClick={() => {
                      console.log(index.my_score)
                      if (index.my_score == "") {
                        store.setItem("ScoreID", index.id)
                        setOpen(true);
                      }
                      else {
                        alert("您已经打过分了！")
                      }
                  }}
                >
                评分
                </a>
                <CollectionCreateForm
                    open={open}
                    onCreate={onCreate}
                    onCancel={() => {
                    setOpen(false);
                }}
                />
              </div>
            </Space>
        ) },
    }
    ];

    useEffect(()=>{
      const getData = async() => {
        var class_name = store.getItem("ClassPage")
        var user_name = store.getItem("UserName")
        var table_data = {
          "course": class_name,
          "user": user_name
        }
        request.post('/api/getAllArticles', table_data).then(  
          res => {  
            dataSource = res.data
            console.log(res.data)
            let tmp = [...dataSource]
            setTableData(tmp)
          }
        ).catch(res => {  // 错误处理
          console.log(res.data.res)
        })
      }
      getData()
    },[])

    return (
      <Table dataSource={TableData} columns={columns1} />
    )
}

export default Table1